import os
import streamlit as st
from datetime import datetime
from typing import Dict, List, Optional, Any, Union
# 导入视图
from views.sidebar_view import SidebarView
from views.dashboard_view import DashboardView
from views.email_settings_view import EmailSettingsView
from views.model_config_view import ModelConfigView
from views.config_files_view import ConfigFilesView
from views.results_view import ResultsView
from views.logs_view import LogsView
from views.analysis_view import AnalysisView
from views.error_records_view import ErrorRecordsView
from views.verification_view import VerificationView

# 导入模型
from sinotrans.utils import Logger
from service.email_analyse import EmlAidata
from service.email_processor import EmailProcessor

class UIController:
    """UI控制器 - 管理所有视图和业务逻辑"""
    
    def __init__(self):
        # 初始化视图
        self.sidebar_view = SidebarView()
        self.dashboard_view = DashboardView()
        self.email_settings_view = EmailSettingsView()
        self.model_config_view = ModelConfigView()
        self.config_files_view = ConfigFilesView()

        # 初始化视图时传入controller引用
        self.results_view = ResultsView()
        self.logs_view = LogsView()
        self.analysis_view = AnalysisView()
        self.error_records_view = ErrorRecordsView()
        self.verification_view = VerificationView()
        
        # 邮件处理器
        self.email_processor: Optional[EmailProcessor] = None
        
        # 完整的session_state初始化（合并原来的两部分逻辑）
        default_forward_patterns = [
            r'-----Original Message-----', r'On\s.+?\s+wrote:\s*$',
            r'^From:\s+.*$', r'^To:\s+.*$', r'^Sent:\s+.*$', r'^Subject:\s+.*$',
            r'-{5,}', r'_{5,}', r'\*{5,}', r'^>\s+.*', r'^转发：\s*.*',
            r'^发件人\s*.*', r'^日期：\s*.*', r'^-----邮件原件-----',
            r'^-----原始邮件-----', r'^INTERNAL', r'发件人:', r'blockquote',
            r'Original Message', r'Best Regards', r'best regards',
            r'Tks & B.Rgds', r'Thanks and Best Regards', r'吴洪兵',
            r'From:', r'中国外运华东有限公司储运分公司', r'Your Sincerely',
            r'敬祝', r'此致敬意', r'田珩玮', r'从现在开始所有欧盟 _国家ETD-3天截提单'
        ]
        
        defaults = {
            'current_menu': 'dashboard',
            'current_submenu': None,
            'is_processing': False,
            'email_processor': None,
            'processing_thread': None,
            'results_temp_total': 0,
            # 队列和相关数据
            'processed_count': 0,
            'email_stats': {
                'processed_count': 0,
                'success_count': 0,
                'error_count': 0,
                'remaining_count': 0,
                'history': [],
                'last_processed': 0
            },
            # 定义需要分析的AI识别字段
            'ai_fields': ['船名', '航次', 'ETD', 'ETA', '提货日期', '船公司', 'MBL', 'HBL', 
                        'ATD', '箱号', '封号', '进仓时间', '出库时间', '进港时间', 'ATA', 
                        '目的港清关完成时间', '送货时间'],
            'skipped_fields': ['AI识别名称', '委托单号', '船公司', '进仓时间', '出库时间', '进港时间', 'ATA', 
                        '目的港清关完成时间', '送货时间', '数据更新时间', '船名_updated_from', '航次_updated_from', 
                        'ETD_updated_from', 'ETA_updated_from', '提货日期_updated_from', '船公司_updated_from', 'MBL_updated_from', 
                        'HBL_updated_from', 'ATD_updated_from', '箱号_updated_from', '封号_updated_from', '进仓时间_updated_from', 
                        '出库时间_updated_from', '进港时间_updated_from', 'ATA_updated_from', '目的港清关完成时间_updated_from', 
                        '送货时间_updated_from'],
            'log_messages': [],
            'last_update_time': datetime.now(),
            'email_data': [],
            # 配置参数（包含所有EmlAidata初始化参数）
            'config_params': {
                # 基础配置
                'email_folder_version': 'V12',
                'max_email_count': 1,
                'max_retries': 5,
                'email_folder': 'INBOX',
                # IMAP配置
                'imap_username': 'sit_RPA-WYWLolp@i.sinotrans.com',# 'sit_RPA-WYWLolp-sb@i.sinotrans.com',
                'imap_password': '29658-cdafr',# '49758-xzckn',
                'imap_server': 'owa.sinotrans.com',
                'imap_port': 993,
                # SMTP配置
                'smtp_username': 'rpa_pro@sinotrans.com',
                'smtp_password': 'wygf2021#Rpa',
                'smtp_server': 'owa.sinotrans.com',
                'smtp_port': 6666,
                # 其他配置
                'max_threads': 3,
                'heartbeat_interval': 20, 
                'processed_uids_max_size': 10, 
                'max_results_memory_limit': 10, 
                'max_deleted_email_limit': 10
            },
            # 模型配置实例（现在只用于forward_patterns）
            'model_config': {
                # 正则表达式配置
                'forward_patterns': default_forward_patterns
            },
            # 数据核验相关
            'verification_data': None,
            'verification_file_uploaded': False,
            'verification_annotations': {},
            'verification_results': None,
            'error_type_options': [
                '识别错误',
                '格式错误',
                '内容缺失',
                '内容冗余',
                '时间格式错误',
                '数字格式错误',
                '逻辑错误',
                '其他错误'
            ]
        }
        
        # 统一初始化所有session_state
        for key, value in defaults.items():
            if key not in st.session_state:
                st.session_state[key] = value

        self._init_logger()
    def _init_logger(self):
        """初始化日志系统"""
        current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        debug_path = os.path.join(current_dir, "logs")
        Logger(debug_path=debug_path)
    def handle_start_processing(self):
        """处理开始邮件处理"""
        try:
            # 只创建邮件处理器，所有实例创建都在EmailProcessor内部完成
            email_processor = EmailProcessor(
                max_workers=st.session_state.config_params.get('max_threads', 3),
                heartbeat_interval=st.session_state.config_params.get('heartbeat_interval', 20), 
                processed_uids_max_size=st.session_state.config_params.get('processed_uids_max_size', 10), 
                max_results_memory_limit=st.session_state.config_params.get('max_results_memory_limit', 10), 
                max_deleted_email_limit=st.session_state.config_params.get('max_deleted_email_limit', 10)
                )
            
            # 保存到session_state
            st.session_state.email_processor = email_processor
            
            # 启动处理
            if email_processor.start():
                st.session_state.is_processing = True
                st.success("✅ 已启动")
            else:
                st.error("❌ 启动失败")
                
        except Exception as e:
            st.error(f"❌ 启动失败：{str(e)}")
    
    def handle_stop_processing(self):
        """处理停止邮件处理"""
        try:
            Logger.info("=== 开始停止处理 ===")
            email_processor = st.session_state.get('email_processor')
            
            if email_processor:
                # 检查当前状态
                if email_processor.is_running:
                    # 尝试停止
                    if email_processor.stop():
                        self.email_processor = None
                        if 'email_processor' in st.session_state:
                            del st.session_state['email_processor']
                        st.session_state.is_processing = False
                        st.success("已停止")
                    else:
                        st.error("❌ 停止失败：处理器停止时出现异常")
                else:
                    # 处理器已经停止，但UI状态未同步
                    self.email_processor = None
                    if 'email_processor' in st.session_state:
                        del st.session_state['email_processor']
                    st.session_state.is_processing = False
                    st.success("已停止（状态已同步）")
            else:
                st.warning("⚠️ 停止失败：处理器未在运行")
                
        except Exception as e:
            Logger.error(f"❌ 停止过程中发生致命异常: {e}")
    def update_stats_from_queue(self):
        """从队列更新统计数据 - 处理debug日志数据"""
        if not st.session_state.email_processor:
            return
            
        updates = st.session_state.email_processor.get_updates()
        
        for update in updates:
            if 'debug_logs' in update:
                # 处理debug日志数据 - 直接替换整个日志列表
                st.session_state.log_messages = update['debug_logs']
                # 记录日志文件信息
                st.session_state.current_log_file = update.get('log_file', 'Unknown')
            
            elif 'stats' in update:
                # 处理统计数据更新
                stats = update['stats']
                
                # 更新email_stats
                old_processed = st.session_state.email_stats['processed_count']
                st.session_state.email_stats.update({
                    'processed_count': stats['processed_count'],
                    'remaining_count': stats['remaining_count'],
                    'success_count': stats['success_count'],
                    'error_count': stats['error_count']
                })

                # 只有在处理数量变化时才添加历史记录
                # 在update_stats_from_queue方法中修改
                if old_processed != stats['processed_count']:
                    # 计算增量值
                    processed_delta = stats['processed_count'] - old_processed
                    old_success = st.session_state.email_stats.get('success_count', 0)
                    old_error = st.session_state.email_stats.get('error_count', 0)
                    success_delta = stats['success_count'] - old_success
                    error_delta = stats['error_count'] - old_error
                    
                    # 存储增量值而不是累积值
                    st.session_state.email_stats['history'].append({
                        'timestamp': update['full_timestamp'],
                        'processed': processed_delta,  # 这个时间点新处理的邮件数
                        'success': success_delta,      # 这个时间点新成功的邮件数
                        'error': error_delta           # 这个时间点新失败的邮件数
                    })
                    
                    # 限制历史数据点数量
                    if len(st.session_state.email_stats['history']) > 50:
                        st.session_state.email_stats['history'] = st.session_state.email_stats['history'][-50:]
                        
    def render_page(self):
        """渲染主页面 - 优化版本"""
        # 只在处理中时才更新统计数据（参考app_ui.py）
        if st.session_state.is_processing:
            self.update_stats_from_queue()
        
        # 渲染侧边栏
        self.sidebar_view.render_menu(
            is_processing=st.session_state.is_processing,
            on_start_callback=self.handle_start_processing,
            on_stop_callback=self.handle_stop_processing
        )
        
        # 渲染主内容区域
        self._render_main_content()
    
    def _render_main_content(self):
        """根据当前菜单渲染主内容"""
        current_menu = st.session_state.get('current_menu', 'dashboard')
        current_submenu = st.session_state.get('current_submenu', None)
        
        if current_menu == 'dashboard':
            self.dashboard_view.render()
        elif current_menu == 'config':
            # 配置管理主菜单，根据子菜单渲染对应页面
            if current_submenu == 'email_settings':
                self.email_settings_view.render()
            elif current_submenu == 'model_config':
                self.model_config_view.render()
            elif current_submenu == 'config_files':
                self.config_files_view.render()
            else:
                # 默认显示邮箱设置
                st.session_state.current_submenu = 'email_settings'
                self.email_settings_view.render()
        elif current_menu == 'results':
            self.results_view.render()
        elif current_menu == 'logs':
            self.logs_view.render()
        elif current_menu == 'result_analysis':
            self.analysis_view.render()
        elif current_menu == 'error_records':
            self.error_records_view.render()
        elif current_menu == 'data_verification':
            # 使用tabs来组织数据核验的不同功能
            tab1, tab2 = st.tabs(["📁 数据核验", "📊 核验结果"])
            
            with tab1:
                self.verification_view.render()
            
            with tab2:
                self.verification_view.render_verification_results()
        else:
            st.error(f"未知页面: {current_menu}")